<template>
  <div class="file-browser">
    <div class="browser-header">
      <n-space align="center">
        <n-icon size="16">
          <FolderOpenOutline />
        </n-icon>
        <span>文件浏览器</span>
        <n-button
          size="small"
          type="primary"
          ghost
          @click="refreshFiles"
          :loading="loading"
        >
          刷新
        </n-button>
      </n-space>
    </div>
    
    <div class="browser-content">
      <!-- 路径导航 -->
      <div class="path-nav">
        <n-breadcrumb>
          <n-breadcrumb-item
            v-for="(path, index) in pathParts"
            :key="index"
            @click="navigateToPath(index)"
            :clickable="index < pathParts.length - 1"
          >
            {{ path }}
          </n-breadcrumb-item>
        </n-breadcrumb>
      </div>
      
      <!-- 文件列表 -->
      <div class="file-list" v-if="!loading">
        <!-- 返回上级目录 -->
        <div
          v-if="currentPath !== '/'"
          class="file-item directory"
          @click="navigateUp"
        >
          <n-icon class="file-icon">
            <ArrowUpOutline />
          </n-icon>
          <span class="file-name">..</span>
          <span class="file-info">返回上级</span>
        </div>
        
        <!-- 目录列表 -->
        <div
          v-for="dir in directories"
          :key="dir.name"
          class="file-item directory"
          @click="navigateToDirectory(dir.name)"
        >
          <n-icon class="file-icon">
            <FolderOutline />
          </n-icon>
          <span class="file-name">{{ dir.name }}</span>
          <span class="file-info">{{ dir.modifiedTime }}</span>
        </div>
        
        <!-- 文件列表 -->
        <div
          v-for="file in files"
          :key="file.name"
          class="file-item file"
          :class="{ selected: selectedFile?.name === file.name }"
          @click="selectFile(file)"
          @dblclick="openFile(file)"
        >
          <n-icon class="file-icon">
            <DocumentTextOutline />
          </n-icon>
          <span class="file-name">{{ file.name }}</span>
          <span class="file-size">{{ formatFileSize(file.size) }}</span>
          <span class="file-info">{{ file.modifiedTime }}</span>
        </div>
        
        <!-- 空状态 -->
        <div v-if="directories.length === 0 && files.length === 0" class="empty-state">
          <n-empty description="此目录为空" />
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <n-spin size="large">
          <template #description>加载文件列表中...</template>
        </n-spin>
      </div>
    </div>
    
    <!-- 文件操作栏 -->
    <div class="file-actions" v-if="selectedFile">
      <n-space>
        <n-button size="small" @click="openFile(selectedFile)">
          <template #icon>
            <n-icon><EyeOutline /></n-icon>
          </template>
          查看
        </n-button>
        <n-button size="small" @click="tailFile(selectedFile)">
          <template #icon>
            <n-icon><PlayOutline /></n-icon>
          </template>
          实时追踪
        </n-button>
        <n-button size="small" @click="downloadFile(selectedFile)">
          <template #icon>
            <n-icon><DownloadOutline /></n-icon>
          </template>
          下载
        </n-button>
      </n-space>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import {
  FolderOpenOutline,
  FolderOutline,
  DocumentTextOutline,
  ArrowUpOutline,
  EyeOutline,
  PlayOutline,
  DownloadOutline
} from '@vicons/ionicons5'
import { useMessage } from 'naive-ui'

interface FileItem {
  name: string
  size: number
  modifiedTime: string
  isDirectory: boolean
  path: string
}

interface DirectoryItem {
  name: string
  modifiedTime: string
  path: string
}

const props = defineProps<{
  connected: boolean
}>()

const emit = defineEmits<{
  fileSelected: [file: FileItem]
  fileOpened: [file: FileItem]
  tailRequested: [file: FileItem]
}>()

const message = useMessage()

// 状态
const loading = ref(false)
const currentPath = ref('/var/log')
const selectedFile = ref<FileItem | null>(null)
const fileList = ref<FileItem[]>([])

// 计算属性
const pathParts = computed(() => {
  return currentPath.value.split('/').filter(part => part !== '')
})

const directories = computed(() => {
  return fileList.value
    .filter(item => item.isDirectory)
    .sort((a, b) => a.name.localeCompare(b.name))
})

const files = computed(() => {
  return fileList.value
    .filter(item => !item.isDirectory)
    .sort((a, b) => a.name.localeCompare(b.name))
})

// 方法
const refreshFiles = async () => {
  if (!props.connected) {
    message.warning('请先连接到BMC服务器')
    return
  }
  
  loading.value = true
  
  try {
    // 模拟获取文件列表
    await simulateFileList()
  } catch (error) {
    message.error('获取文件列表失败')
  } finally {
    loading.value = false
  }
}

const simulateFileList = async () => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 500 + Math.random() * 1000))
  
  // 模拟不同目录的文件列表
  const mockFiles: FileItem[] = []
  
  if (currentPath.value === '/var/log') {
    mockFiles.push(
      {
        name: 'messages',
        size: 1024 * 1024 * 2.5, // 2.5MB
        modifiedTime: '2024-01-10 14:25:30',
        isDirectory: false,
        path: '/var/log/messages'
      },
      {
        name: 'dmesg',
        size: 1024 * 512, // 512KB
        modifiedTime: '2024-01-10 14:20:15',
        isDirectory: false,
        path: '/var/log/dmesg'
      },
      {
        name: 'sel_log',
        size: 1024 * 256, // 256KB
        modifiedTime: '2024-01-10 14:23:45',
        isDirectory: false,
        path: '/var/log/sel_log'
      },
      {
        name: 'secure',
        size: 1024 * 1024 * 1.2, // 1.2MB
        modifiedTime: '2024-01-10 14:22:10',
        isDirectory: false,
        path: '/var/log/secure'
      },
      {
        name: 'boot.log',
        size: 1024 * 128, // 128KB
        modifiedTime: '2024-01-10 10:15:00',
        isDirectory: false,
        path: '/var/log/boot.log'
      },
      {
        name: 'httpd',
        size: 0,
        modifiedTime: '2024-01-10 12:00:00',
        isDirectory: true,
        path: '/var/log/httpd'
      },
      {
        name: 'nginx',
        size: 0,
        modifiedTime: '2024-01-10 11:30:00',
        isDirectory: true,
        path: '/var/log/nginx'
      }
    )
  } else if (currentPath.value === '/var/log/httpd') {
    mockFiles.push(
      {
        name: 'access.log',
        size: 1024 * 1024 * 5.2, // 5.2MB
        modifiedTime: '2024-01-10 14:25:00',
        isDirectory: false,
        path: '/var/log/httpd/access.log'
      },
      {
        name: 'error.log',
        size: 1024 * 256, // 256KB
        modifiedTime: '2024-01-10 14:20:30',
        isDirectory: false,
        path: '/var/log/httpd/error.log'
      }
    )
  } else if (currentPath.value === '/var/log/nginx') {
    mockFiles.push(
      {
        name: 'access.log',
        size: 1024 * 1024 * 3.8, // 3.8MB
        modifiedTime: '2024-01-10 14:24:45',
        isDirectory: false,
        path: '/var/log/nginx/access.log'
      },
      {
        name: 'error.log',
        size: 1024 * 128, // 128KB
        modifiedTime: '2024-01-10 14:18:20',
        isDirectory: false,
        path: '/var/log/nginx/error.log'
      }
    )
  }
  
  fileList.value = mockFiles
}

const navigateToPath = (index: number) => {
  const newPath = '/' + pathParts.value.slice(0, index + 1).join('/')
  currentPath.value = newPath
  selectedFile.value = null
  refreshFiles()
}

const navigateUp = () => {
  const parts = currentPath.value.split('/').filter(part => part !== '')
  if (parts.length > 1) {
    parts.pop()
    currentPath.value = '/' + parts.join('/')
  } else {
    currentPath.value = '/'
  }
  selectedFile.value = null
  refreshFiles()
}

const navigateToDirectory = (dirName: string) => {
  currentPath.value = currentPath.value.endsWith('/') 
    ? currentPath.value + dirName
    : currentPath.value + '/' + dirName
  selectedFile.value = null
  refreshFiles()
}

const selectFile = (file: FileItem) => {
  selectedFile.value = file
  emit('fileSelected', file)
}

const openFile = (file: FileItem) => {
  emit('fileOpened', file)
}

const tailFile = (file: FileItem) => {
  emit('tailRequested', file)
}

const downloadFile = (file: FileItem) => {
  message.info(`开始下载文件: ${file.name}`)
  // 这里将来实现实际的文件下载
}

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}

// 生命周期
onMounted(() => {
  if (props.connected) {
    refreshFiles()
  }
})

// 监听连接状态变化
watch(() => props.connected, (newVal) => {
  if (newVal) {
    refreshFiles()
  } else {
    fileList.value = []
    selectedFile.value = null
  }
})
</script>

<style scoped>
.file-browser {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #fafafa;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
}

.browser-header {
  padding: 12px;
  background: #f5f5f5;
  border-bottom: 1px solid #d9d9d9;
  border-radius: 6px 6px 0 0;
}

.browser-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.path-nav {
  padding: 8px 12px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
}

.file-list {
  flex: 1;
  overflow-y: auto;
  padding: 4px;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  margin: 2px 0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.file-item:hover {
  background: #f0f0f0;
}

.file-item.selected {
  background: #e6f7ff;
  border: 1px solid #91d5ff;
}

.file-item.directory {
  color: #1890ff;
}

.file-item.file {
  color: #262626;
}

.file-icon {
  margin-right: 8px;
  flex-shrink: 0;
}

.file-name {
  flex: 1;
  font-weight: 500;
  margin-right: 12px;
}

.file-size {
  min-width: 80px;
  text-align: right;
  color: #8c8c8c;
  font-size: 12px;
  margin-right: 12px;
}

.file-info {
  min-width: 120px;
  text-align: right;
  color: #8c8c8c;
  font-size: 12px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.file-actions {
  padding: 12px;
  background: #f5f5f5;
  border-top: 1px solid #d9d9d9;
  border-radius: 0 0 6px 6px;
}
</style>